package com.example.wanandroid.activity.main

import android.content.Context
import android.content.res.Resources
import android.graphics.Color
import android.graphics.ColorFilter
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.drawable.Drawable
import android.graphics.drawable.VectorDrawable
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.graphics.drawable.DrawableCompat

class BottomNaviView(context: Context, attrs: AttributeSet? = null) : LinearLayout(context, attrs) {
    private var itemViews = ArrayList<View>()
    private var iconViews = ArrayList<ImageView>()
    private var titleViews = ArrayList<TextView>()
    private var onItemClickListener: OnItemClickListener? = null
    private lateinit var items: List<NaviItem>

    class NaviItem(val iconId: Int,val selectedIconId: Int, val title: String)

    fun addNaviItems(items: List<NaviItem>) {
        this.items = items

        items.forEach {
            val itemView = LinearLayout(this.context)
            itemView.orientation = VERTICAL
            itemView.gravity = Gravity.CENTER
            itemView.isClickable = true
            addView(itemView,LayoutParams(0, LayoutParams.MATCH_PARENT, 1f))
            itemViews.add(itemView)

            val iconView = ImageView(this.context)
            itemView.addView(iconView,LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT))
            iconViews.add(iconView)

            val titleView = TextView(this.context)
            titleView.text = it.title
            itemView.addView(titleView,LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT))
            titleViews.add(titleView)
        }

        setSelectedPosition(0)

        itemViews.indices.forEach {
            itemViews[it].setOnClickListener { view ->
                onItemClickListener?.onItemClicked(view, it)
                setSelectedPosition(it)
            }
        }
    }

    interface OnItemClickListener {
        fun onItemClicked(view: View, position: Int)
    }

    fun setOnItemClickListener(l: OnItemClickListener) {
        onItemClickListener = l
    }

    fun setSelectedPosition(selectedPosition: Int) {
        itemViews.indices.forEach {
            if (it == selectedPosition) {
                iconViews[it].setImageResource(items[it].selectedIconId)
                titleViews[it].setTextColor(Color.BLUE)
            } else {
                iconViews[it].setImageResource(items[it].iconId)
                titleViews[it].setTextColor(Color.BLACK)
            }
        }
    }

}